package demos;

import java.util.Stack;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Lock主要和Condition结合使用
 * 精准通知，精准唤醒
 */
class ConditionSource {
    Lock lock = new ReentrantLock();
    Condition conditionA = lock.newCondition();
    Condition conditionB = lock.newCondition();
    Condition conditionC = lock.newCondition();

    private int flag = 1;

    public void sayA() throws InterruptedException {
        lock.lock();
        try {
            while (flag != 1) {
                conditionA.await();
            }
            for (int i = 0; i < 5; i++) {
                System.out.println("AA");
            }
            flag = 2;
            conditionB.signal();
        } finally {
            lock.unlock();
        }
    }
    public void sayB() throws InterruptedException {
        lock.lock();
        try {
            while (flag != 2) {
                conditionB.await();
            }
            for (int i = 0; i < 10; i++) {
                System.out.println("BB");
            }
            flag = 3;
            conditionC.signal();
        } finally {
            lock.unlock();
        }
    }
    public void sayC() throws InterruptedException {
        lock.lock();
        try {
            while (flag != 3) {
                conditionC.await();
            }
            for (int i = 0; i < 15; i++) {
                System.out.println("CC");
            }
            flag = 1;
            conditionA.signal();
        } finally {
            lock.unlock();
        }
    }

}


/**
 * 多线程之间按照顺序调用，实现 A->B->C
 * 三个线程启动要求如下：
 * <p>
 * AA打印5次，BB打印10次，CC打印15次
 * 接着
 * AA打印5次，BB打印10次，CC打印15次
 * ...... 来10轮
 *
 * 1. 线程操作资源类
 * 2. 判断/干活/通知
 * 3. 多线程交互，防止虚假唤醒，循环判断
 * 4. 标志位
 */
public class ConditionDemo {
    public static void main(String[] args) {
        ConditionSource source = new ConditionSource();
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    source.sayA();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    source.sayB();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    source.sayC();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

    }
}
